<!DOCTYPE html>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
--><html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
<meta name="generator" content="joDoc">
<title>Apache Cordova API Documentation</title>
<link rel="stylesheet" type="text/css" href="index.css">
<link rel="stylesheet" type="text/css" href="mobile.css" media="only screen and (max-device-width: 1024px)">
<link rel="stylesheet" type="text/css" href="prettify/prettify.css">
</head>
<body>
        <div id="header">
            <h1><a href="index.html">Apache <strong>Cordova</strong> Documentation</a></h1>
            <small>
                <select><optgroup label="English" value="en">
<option value="edge">edge</option>
<option value="2.2.0rc2">2.2.0rc2</option>
<option value="2.2.0rc1">2.2.0rc1</option>
<option selected value="2.2.0">2.2.0</option>
<option value="2.1.0rc2">2.1.0rc2</option>
<option value="2.1.0rc1">2.1.0rc1</option>
<option value="2.1.0">2.1.0</option>
<option value="2.0.0rc1">2.0.0rc1</option>
<option value="2.0.0">2.0.0</option>
<option value="1.9.0rc1">1.9.0rc1</option>
<option value="1.9.0">1.9.0</option>
<option value="1.8.1">1.8.1</option>
<option value="1.8.0rc1">1.8.0rc1</option>
<option value="1.8.0">1.8.0</option>
<option value="1.7.0rc1">1.7.0rc1</option>
<option value="1.7.0">1.7.0</option>
<option value="1.6.1">1.6.1</option>
<option value="1.6.0rc1">1.6.0rc1</option>
<option value="1.6.0">1.6.0</option>
<option value="1.5.0rc1">1.5.0rc1</option>
<option value="1.5.0">1.5.0</option>
<option value="1.4.1">1.4.1</option>
<option value="1.4.0rc1">1.4.0rc1</option>
<option value="1.4.0">1.4.0</option>
<option value="1.3.0">1.3.0</option>
<option value="1.2.0">1.2.0</option>
<option value="1.1.0">1.1.0</option>
<option value="1.0.0rc3">1.0.0rc3</option>
<option value="1.0.0rc2">1.0.0rc2</option>
<option value="1.0.0rc1">1.0.0rc1</option>
<option value="1.0.0">1.0.0</option>
<option value="0.9.6">0.9.6</option>
<option value="0.9.5.1">0.9.5.1</option>
<option value="0.9.5">0.9.5</option>
<option value="0.9.4">0.9.4</option>
<option value="0.9.3">0.9.3</option>
<option value="0.9.2">0.9.2</option>
</optgroup>
<optgroup label="Español" value="es"><option value="1.0.0">1.0.0</option></optgroup>
<optgroup label="Français" value="fr">
<option value="1.3.0">1.3.0</option>
<option value="1.2.0">1.2.0</option>
<option value="1.1.0">1.1.0</option>
</optgroup>
<optgroup label="Japanese" value="jp">
<option value="2.0.0">2.0.0</option>
<option value="1.9.0">1.9.0</option>
<option value="1.8.1">1.8.1</option>
<option value="1.7.0">1.7.0</option>
<option value="0.9.5">0.9.5</option>
</optgroup>
<optgroup label="Korean" value="kr"><option value="2.0.0">2.0.0</option></optgroup></select></small>
        </div>
        <div id="subheader">
            <h1>Developing a Plugin on Android</h1>
            <small><select><option value="Developing%2520a%2520Plugin%2520on%2520Android">Developing a Plugin on Android</option>
<option value="Developing%20a%20Plugin%20on%20Android_plugin_class_mapping">      - Plugin Class Mapping</option>
<option value="Developing%20a%20Plugin%20on%20Android_writing_an_android_java_plugin">      - Writing an Android Java Plugin</option>
<option value="Developing%20a%20Plugin%20on%20Android_debugging_plugins">      - Debugging Plugins</option>
<option value="Developing%20a%20Plugin%20on%20Android_common_pitfalls">      - Common Pitfalls</option>
<option value="Developing%20a%20Plugin%20on%20Android_use_the_source">      - Use the Source</option></select></small>
        </div>

        <div id="sidebar">
            <div class="vertical_divider"></div>
        <h1>API Reference</h1>
<ul>
<li><a href="cordova_accelerometer_accelerometer.md.html#Accelerometer">Accelerometer</a></li>
<li><a href="cordova_camera_camera.md.html#Camera">Camera</a></li>
<li><a href="cordova_media_capture_capture.md.html#Capture">Capture</a></li>
<li><a href="cordova_compass_compass.md.html#Compass">Compass</a></li>
<li><a href="cordova_connection_connection.md.html#Connection">Connection</a></li>
<li><a href="cordova_contacts_contacts.md.html#Contacts">Contacts</a></li>
<li><a href="cordova_device_device.md.html#Device">Device</a></li>
<li><a href="cordova_events_events.md.html#Events">Events</a></li>
<li><a href="cordova_file_file.md.html#File">File</a></li>
<li><a href="cordova_geolocation_geolocation.md.html#Geolocation">Geolocation</a></li>
<li><a href="cordova_globalization_globalization.md.html#Globalization">Globalization</a></li>
<li><a href="cordova_media_media.md.html#Media">Media</a></li>
<li><a href="cordova_notification_notification.md.html#Notification">Notification</a></li>
<li><a href="cordova_splashscreen_splashscreen.md.html#Splashscreen">Splashscreen</a></li>
<li><a href="cordova_storage_storage.md.html#Storage">Storage</a></li>
</ul>
<h1>Guides</h1>
<ul>
<li><a href="guide_getting-started_index.md.html#Getting%20Started%20Guides">Getting Started Guides</a></li>
<li><a href="guide_command-line_index.md.html#Command-Line%20Usage">Command-Line Usage</a></li>
<li><a href="guide_upgrading_index.md.html#Upgrading%20Guides">Upgrading Guides</a></li>
<li><a href="guide_project-settings_index.md.html#Project%20Settings">Project Settings</a></li>
<li><a href="guide_plugin-development_index.md.html#Plugin%20Development%20Guide">Plugin Development Guide</a></li>
<li><a href="guide_whitelist_index.md.html#Domain%20Whitelist%20Guide">Domain Whitelist Guide</a></li>
<li><a href="guide_cordova-webview_index.md.html#Embedding%20WebView">Embedding WebView</a></li>
<li><a href="_index.html">Keyword Index</a></li>
</ul>
</div>

        <div id="scrollable">
            <div id="content">
                <h1><a name="Developing%20a%20Plugin%20on%20Android">Developing a Plugin on Android</a></h1>

<p>Writing a plugin requires an understanding of the architecture of Cordova-Android. Cordova-Android consists
of an Android WebView with hooks attached to it. These plugins are represented as class mappings in the config.xml
file.</p>

<p>A plugin will consist of at least a single Java class that extends the <code>CordovaPlugin</code> class. A plugin must override one
of the <code>execute</code> methods from <code>CordovaPlugin</code>. In addition to this, there is a best practice that
the plugin should handle <a href="cordova_events_events.md.html#pause">pause</a> and <a href="cordova_events_events.md.html#resume">resume</a> events, and should handle message passing between plugins.
Plugins with long-running requests, background activity (e.g. playing media), listeners or internal state should implement the <code>onReset()</code> method as well. This method is run when the <code>WebView</code> navigates to a new page or refreshes, which reloads the Javascript.</p>

<h2>
<a name="Developing%20a%20Plugin%20on%20Android_plugin_class_mapping">Plugin Class Mapping</a>
</h2>

<p>The JavaScript portion of a plugin always uses the <code>cordova.exec</code> method as follows:</p>

<pre class="prettyprint"><code>exec(&lt;successFunction&gt;, &lt;failFunction&gt;, &lt;service&gt;, &lt;action&gt;, [&lt;args&gt;]);
</code></pre>

<p>This will marshall a request from the WebView to the Android native
side, more or less boiling down to calling the <code>action</code> method on the
<code>service</code> class, with the arguments passed in the <code>args</code> Array.</p>

<p>Whether you distribute your plugin as Java file or as a JAR of its own, the plugin must be added to the <code>config.xml</code> file in your Cordova-Android application's <code>res/xml/</code> folder.</p>

<pre class="prettyprint"><code>&lt;plugin name="&lt;service_name&gt;" value="&lt;full_name_including_namespace&gt;"/&gt;
</code></pre>

<p>The service name should match what you use in the JavaScript <code>exec</code> call, and the value will be the full name of the Java class including the namespace. Without this added, the plugin may compile but 
will not be reachable by Cordova.</p>

<h2>
<a name="Developing%20a%20Plugin%20on%20Android_writing_an_android_java_plugin">Writing an Android Java Plugin</a>
</h2>

<p>We have JavaScript to fire off a plugin request to the native side. We
have the Android Java plugin mapped properly via the <code>config.xml</code> file.
So what does the final Android Java Plugin class look like?</p>

<p>What gets dispatched to the plugin via JavaScript's <code>exec</code> function gets
passed into the Plugin class's <code>execute</code> method. Most <code>execute</code>
implementations look like this:</p>

<pre class="prettyprint"><code>@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if ("beep".equals(action)) {
        this.beep(args.getLong(0));
        callbackContext.success();
        return true;
    }
    return false;  // Returning false results in a "MethodNotFound" error.
}
</code></pre>

<p>We compare the value of the <code>action</code> parameter, and dispatch
the request off to a (private) method in the class, optionally passing
some of the parameters to the method.</p>

<p>When catching exceptions and returning errors, it's important that the error we return to JavaScript match the Java exception as much as possible, for clarity.</p>

<h3>Threading</h3>

<p>JavaScript in the WebView does <em>not</em> run on the UI thread. It runs on
the WebCore thread. The <code>execute</code> method also runs on the WebCore thread.</p>

<p>If you need to interact with the UI, you should use the following:</p>

<pre class="prettyprint"><code>@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
    if ("beep".equals(action)) {
        final long duration = args.getLong(0);
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                ...
                callbackContext.success(); // Thread-safe.
            }
        });
        return true;
    }
    return false;
}
</code></pre>

<p>If you do not need to run on the UI thread, but do not want to block the WebCore thread:</p>

<pre class="prettyprint"><code>@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
    if ("beep".equals(action)) {
        final long duration = args.getLong(0);
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                ...
                callbackContext.success(); // Thread-safe.
            }
        });
        return true;
    }
    return false;
}
</code></pre>

<h3>Echo Android Plugin Example</h3>

<p>We would add the following to our config.xml:</p>

<pre class="prettyprint"><code>&lt;plugin name="Echo" value="org.apache.cordova.plugin.Echo" /&gt;
</code></pre>

<p>Then we would add the following file to
<code>src/org/apache/cordova/plugin/Echo.java</code> inside our Cordova-Android
application:</p>

<pre class="prettyprint"><code>package org.apache.cordova.plugin;

import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This class echoes a string called from JavaScript.
 */
public class Echo extends CordovaPlugin {
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("echo")) {
            String message = args.getString(0); 
            this.echo(message);
            return true;
        }
        return false;
    }

    private void echo(String message, CallbackContext callbackContext) {
        if (message != null &amp;&amp; message.length() &gt; 0) { 
            callbackContext.success(message);
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }
}
</code></pre>

<p>Let's take a look at the code. At the top we have all of the necessary
Cordova <code>imports</code>. Our class extends from <code>CordovaPlugin</code>. We override
the execute() method in order to recieve messages from exec(). Our method
first compares against <code>action</code>: this plugin only supports
one action, the <code>echo</code> action. Any other action will return false, which
results in an error of type <code>INVALID_ACTION</code> - this will translate
into an error callback invocation on the JavaScript side. Next, we grab
the echo string using the <code>getString</code> method on our <code>args</code>, telling it
we want to get the 0th parameter in the parameter array. We do a bit of
parameter checking: make sure it is not <code>null</code>, and make sure it is not
a zero-length string. If it is, we call callbackContext.error() (which,
by now, you should know will invoke the error callback). If all of those
checks pass, then we call callbackContext.success(), and pass in the
<code>message</code> string we received as a parameter. This will finally translate
into a success callback invocation on the JavaScript side. It will also
pass the <code>message</code> parameter as a parameter into the JavaScript success
callback function.</p>

<h2>
<a name="Developing%20a%20Plugin%20on%20Android_debugging_plugins">Debugging Plugins</a>
</h2>

<p>Eclipse can be used to debug an Android project, and the plugins can be debugged if the Java source is included in the project. Only the latest version of the Android Dev Tools is known to allow source code attachment to JAR dependencies, this is not fully supported at this time.</p>

<h2>
<a name="Developing%20a%20Plugin%20on%20Android_common_pitfalls">Common Pitfalls</a>
</h2>

<ul>
<li>Plugins have access to a <code>CordovaInterface</code> object. This object has access to the Android <code>Activity</code> that is running the application. This is the <code>Context</code> required to launch
a new Android <code>Intent</code>. The <code>CordovaInterface</code> allows plugins to start an <code>Activity</code> for a result, and to set the callback plugin for when the <code>Intent</code> comes back to the application. This is important, since the
<code>Intent</code>s system is how Android communicates between processes.</li>
<li>Plugins do not have direct access to the <code>Context</code> as they have in the past. The legacy <code>ctx</code> member is deprecated, and will be removed six months after 2.0 is released. All the methods that <code>ctx</code> has exist on the <code>Context</code>, so both <code>getContext()</code> and <code>getActivity()</code> are capable of returning the proper object required.</li>
</ul>
<h2>
<a name="Developing%20a%20Plugin%20on%20Android_use_the_source">Use the Source</a>
</h2>

<p>One of the best ways to prepare yourself to write your own plugin is to
have a <a class="external" href="https://github.com/apache/incubator-cordova-android/tree/master/framework/src/org/apache/cordova">look at other plugins that already exist</a>.</p>

<p>You should also read through the comments in <a class="external" href="https://github.com/apache/incubator-cordova-android/blob/master/framework/src/org/apache/cordova/api/CordovaPlugin.java">CordovaPlugin.java</a>.</p>

            </div>
        </div>

        <!-- Functionality and Syntax Highlighting -->
        <script type="text/javascript" src="index.js"></script><script type="text/javascript" src="prettify/prettify.js"></script>
</body>
</html>
